package com.bkhc.common.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.read.metadata.ReadSheet;
import org.springframework.util.CollectionUtils;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ExcelUtil {

    private static Sheet initSheet;

    static {
        initSheet = new Sheet(1, 0);
        initSheet.setSheetName("报价单");
        //设置自适应宽度
        initSheet.setAutoWidth(Boolean.TRUE);
    }

    public static void generateExcel(List<? extends BaseRowModel> data,OutputStream outputStream){
        if(CollectionUtils.isEmpty(data)){
            return ;
        }
        Sheet sheet = initSheet;
        sheet.setClazz(data.get(0).getClass());
        ExcelWriter writer = null;
        writer = EasyExcelFactory.getWriter(outputStream);
        writer.write(data,sheet);
        writer.finish();
    }

    public static void writeExcelNoMapping(List<List<Object>> data, ServletOutputStream outputStream, List<String> head){
        Sheet sheet = initSheet;
        if(!CollectionUtils.isEmpty(head)){
            List<List<String>> list = new ArrayList<>();
            head.forEach(h->list.add(Collections.singletonList(h)));
            sheet.setHead(list);
        }
//        try {
//            FileOutputStream outputStream1 = new FileOutputStream("C:\\zhengyun\\order.xlsx");
//            ExcelWriter write = EasyExcelFactory.getWriter(outputStream1);
//            write.write1(data,sheet);
//            write.finish();
//            outputStream1.close();
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        ExcelWriter write = EasyExcelFactory.getWriter(outputStream);
        write.write1(data,sheet);
        write.finish();
    }

    public static Object excelRead(InputStream inputStream){
        NoModleDataListener listener = new NoModleDataListener();
        //ExcelReader reader = EasyExcelFactory.readBySax(inputStream,new Sheet(1, 1),listener);
        //reader.read(new Sheet(0));
        ExcelReader excelReader = EasyExcel.read(inputStream,  listener).build();
        ReadSheet readSheet = EasyExcel.readSheet(0).build();
        excelReader.read(readSheet);
        excelReader.finish();
        Object object = listener.getResult();
        return object;
    }
}
